package services

import (
	"errors"
	"fmt"
	"github.com/labstack/echo/v4"
	"longmen/server/pkg/common/api_models"
	utils2 "longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_main"
)

func (s *Service) GetAnnouncementList(page, size int) ([]*api_models.GetAnnouncementListResp, error) {
	fName := "GetAnnouncementList"
	announcementList, err := db_main.GetAnnouncementList(nil, page, size)
	if err != nil {
		return nil, fmt.Errorf("%s%s", utils2.Convert(fName), err.Error())
	}
	resp := make([]*api_models.GetAnnouncementListResp, 0)
	for _, announcement := range announcementList {
		runes := []rune(utils2.TrimHtml(announcement.Content))
		i := 50
		if len(runes) < 50 {
			i = len(runes)
		}
		resp = append(resp, &api_models.GetAnnouncementListResp{
			Id:         announcement.Id,
			Title:      announcement.Title,
			Content:    string(runes[0:i]),
			CreateTime: announcement.CreateTime.Unix(),
		})
	}
	return resp, nil
}

func (s *Service) GetLastAnnouncement() (*api_models.GetLastAnnouncementResp, error) {
	fName := "GetLastAnnouncement"
	var resp *api_models.GetLastAnnouncementResp
	announcementList, err := db_main.GetAnnouncementList(nil, 1, 1)
	if err != nil {
		return nil, fmt.Errorf("%s%s", utils2.Convert(fName), err.Error())
	}
	if len(announcementList) == 0 {
		return nil, errors.New("没有公告,请在后台填充!")
	}
	for _, announcement := range announcementList {
		resp = &api_models.GetLastAnnouncementResp{
			Id:         announcement.Id,
			Title:      announcement.Title,
			CreateTime: announcement.CreateTime.Unix(),
		}
	}
	return resp, nil
}

func (s *Service) GetAnnouncement(id int) (*api_models.GetAnnouncementResp, error) {
	fName := "GetAnnouncementList"
	announcementList, err := db_main.GetAnnouncementList(echo.Map{"id": id}, 1, 1)
	if err != nil {
		return nil, fmt.Errorf("%s%s", utils2.Convert(fName), err.Error())
	}
	resp := &api_models.GetAnnouncementResp{}
	for _, announcement := range announcementList {
		resp = &api_models.GetAnnouncementResp{
			Title:      announcement.Title,
			Content:    announcement.Content,
			CreateTime: announcement.CreateTime.Unix(),
		}
		break
	}
	return resp, nil
}
